package com.cosw.sdkShanghaiCA;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.cosw.util.StringUtil;

public class CertManager {
	RSAPrivateCrtKey prikey;
	RSAPublicKey pubkey;
	X509Certificate oCert;

	short kenLen; // 只支持1024和2048;

	public void setKenLen() {
		kenLen = (short) pubkey.getModulus().toByteArray().length;
		kenLen -= (short) (kenLen % 128);
	}

	public byte[] getN() {
		byte[] nArr = pubkey.getModulus().toByteArray();
		if (nArr.length > kenLen) {
			return StringUtil.subBytes(nArr, (short) (nArr.length - kenLen),
					(short) kenLen);
		}

		return nArr;
	}

	public byte[] getE() {
		return pubkey.getPublicExponent().toByteArray();
	}

	public boolean parseCerX509(byte[] cert) {
		try {
			// 读取证书文件
			InputStream inStream = new ByteArrayInputStream(cert);
			// 创建X509工厂类
			CertificateFactory cf = CertificateFactory.getInstance("X.509");
			// 创建证书对象
			oCert = (X509Certificate) cf.generateCertificate(inStream);
			inStream.close();
			SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd");
			String info = null;
			// 获得证书版本
			info = String.valueOf(oCert.getVersion());
			System.out.println("证书版本:" + info);
			// 获得证书序列号
			info = oCert.getSerialNumber().toString(16);
			System.out.println("证书序列号:" + info);
			// 获得证书有效期
			Date beforedate = oCert.getNotBefore();
			info = dateformat.format(beforedate);
			System.out.println("证书生效日期:" + info);
			Date afterdate = oCert.getNotAfter();
			info = dateformat.format(afterdate);
			System.out.println("证书失效日期:" + info);
			// 获得证书主体信息
			info = oCert.getSubjectDN().getName();
			System.out.println("证书拥有者:" + info);
			// 获得证书颁发者信息
			info = oCert.getIssuerDN().getName();
			System.out.println("证书颁发者:" + info);
			// 获得证书签名算法名称
			info = oCert.getSigAlgName();
			System.out.println("证书签名算法:" + info);

			pubkey = (RSAPublicKey) oCert.getPublicKey();
			System.out.println("公钥N:"
					+ StringUtil.byteArrayToHexString(pubkey.getModulus()
							.toByteArray()));

			System.out.println("公钥E:"
					+ StringUtil.byteArrayToHexString(pubkey
							.getPublicExponent().toByteArray()));

			/*
			 * byte[] byt = oCert.getExtensionValue("1.2.86.11.7.9"); String
			 * strExt = new String(byt); System.out.println("证书扩展域:" + strExt);
			 * byt = oCert.getExtensionValue("1.2.86.11.7.1.8"); String strExt2
			 * = new String(byt); System.out.println("证书扩展域2:" + strExt2);
			 */

			setKenLen();

			return true;
		} catch (Exception e) {
			System.out.println("解析证书出错！");
		}

		return false;
	}// end showCertInfo
}